import {
  createOrder,
  getAddressInfo,
  getDefaultAddress,
  addFormId,
  getUseCoupon
} from '../../../api.js'

Page({
  data: {
    decrease: 0,
    opt_lis: {},
    coupon: '',
    formIdString: '',
    formIdString_type: '',
    coupon_alert: true,
    couponLis: [],
    couponIndex: '',
    ticker_price: '',
    pay_price: '',
    total_price: '',
    order_enter_type: '',
    zhiyou:false,
    successfulActivities:false
  },
  onLoad: function (options) {
    console.log(options)
    this.checkIfBind()
    this.init(options)
    if (options.order_enter_type == 4){
      this.data.successfulActivities = true
    }
    this.getDefaultAddress()
    this.setData({
      opt_lis: options.product,
      order_enter_type: options.order_enter_type,
      successfulActivities: this.data.successfulActivities
    })
  },
  onShow() {
    getApp().startpage(new Date().getTime())
    this.checkAddress()
  },
  // 检查是否绑定了手机 
  checkIfBind() {
    let isBind = getApp().globalData.Store.user.phone
    if (!isBind) {
      wx.showToast({
        title: "您还未绑定手机号, 正在再跳转绑定页面",
        icon: "none"
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/public/bindphone/bindphone',
        })
      }, 1000)
    }
  },
  // 初始化获取商品
  init(options) {
    let pro = decodeURIComponent(options.product)
    let prod = pro.replace(/\s*/g, "")
    let product = JSON.parse(prod)
    this.quanlis(product)
    var total = 0;
    var that = this
    console.log(product)
    for (var i = 0; i < product.length; i++) {
      if (Number(product[i].activity_price) != 0 && product[i].activity_price != 'null') {
        total = total + Number(product[i].activity_price)
      } else {
        total = total + Number(product[i].price)
      }
      console.log(product[i])
      if (product[i].business_country != '中国'){
        that.setData({
          zhiyou:true
        })
      }
    }
    this.setData({
      product,
      total
    })
  },
  // 获取默认地址
  getDefaultAddress() {
    let token = getApp().globalData.Store.token
    getDefaultAddress(token).then(res => {
      if (res.data.code === 666) {
        this.setData({
          pickAddress: res.data.data
        })
      }
    })
  },
  // 检查是否地址已选择
  checkAddress() {
    let pickAddress = wx.getStorageSync("pickAddress")
    let token = getApp().globalData.Store.token
    if (!pickAddress && !this.data.pickAddress) {
      return
    }
    pickAddress = pickAddress || this.data.pickAddress.id
    getAddressInfo(token, pickAddress).then(res => {
      if (res.data.code === 666) {
        this.setData({
          pickAddress: res.data.data
        })
      } else {
        this.setData({
          pickAddress: null
        })
      }
    })
    // 使用完之后立即移除缓存
    wx.removeStorageSync("pickAddress")
  },
  // input 绑定 data-key 作为键值 
  inputModel(e) {
    let key = e.target.dataset.key
    let value = e.detail.value
    this.setData({
      [key]: value
    })
  },
  // 生成订单
  addOrder() {
    var that = this
    if (!this.validateParams()) {
      return;
    }
    if (this.data.couponIndex === '') {

    }
    let token = getApp().globalData.Store.token
    let product_ids = this.data.product.map(a => a.product_id || a.id);
    let delivery_id = this.data.pickAddress.id
    // let pay_price = this.data.couponIndex === '' ? this.data.total : this.data.couponLis.data[this.data.couponIndex].pay_price
    let pay_price = ''
    if (that.data.successfulActivities){
      pay_price = that.data.product[0].cut_price
    }else{
      pay_price = that.data.couponIndex === '' ? that.data.total : that.data.couponLis.data[that.data.couponIndex].pay_price
    }
    let ticket_id = this.data.couponIndex === '' ? '' : this.data.couponLis.data[this.data.couponIndex].id
    let remark = this.data.remark
    let order_enter_type = this.data.order_enter_type
    createOrder(token,
      product_ids,
      delivery_id,
      pay_price,
      ticket_id,
      remark,
      order_enter_type).then(res => {
        if (res.data.code === 666) {
          wx.hideLoading()
          wx.redirectTo({
            url: `/pages/money/submit/submit?batchcode=${res.data.data.batchcode}`,
          })
        } else {
          that.setData({
            formIdString_type: ''
          })
          wx.showToast({
            title: res.data.msg,
            icon: "none"
          })
        }
      })
  },
  // 检查必须参数
  validateParams() {
    if (!this.data.pickAddress) {
      wx.showToast({
        title: "请先选择收货地址",
        icon: 'none'
      })
      return false
    } else {
      return true
    }
  },
  paymentCoupon() {
    var that = this
    that.setData({
      coupon_alert: false
    })
  },
  formSubmit: function (e) {
    if (!this.validateParams()) {
      return;
    }
    wx.showLoading({
      title: '正在生成订单',
    })
    var that = this
    var token = getApp().globalData.Store.token
    if (!that.data.formIdString_type) {
      that.addOrder()
    }
    addFormId(
      token,
      e.detail.formId,
      1
    ).then(res => {
    })
    that.setData({
      formIdString: e.detail.formId + "," + that.data.formIdString,
      formIdString_type: 1
    })
  },
  coupon_sure(e) {
    var index = e.currentTarget.dataset.ind
    var that = this
    this.setData({
      coupon_alert: true,
      couponIndex: index,
      ticker_price: that.data.couponLis.data[index].ticker_price,
      pay_price: that.data.couponLis.data[index].pay_price,
      total_price: that.data.couponLis.data[index].total_price
    })
  },
  // 获取优惠券
  quanlis(lis) {
    var lisid = []
    var that = this
    for (var i = 0; i < lis.length; i++) {
      lisid.push(lis[i].id)
    }
    getUseCoupon(
      getApp().globalData.Store.token,
      lisid
    ).then(res => {
      if (res.data.code == 666) {
        if (res.data.data.data.length) {
          that.data.couponIndex = 0
          that.data.ticker_price = res.data.data.data[0].ticker_price
          that.data.pay_price = res.data.data.data[0].pay_price
          that.data.total_price = res.data.data.data[0].total_price
        } else {
          that.data.couponIndex = ''
          that.data.pay_price = that.data.total
          that.data.ticker_price = 0
          that.data.total_price = that.data.total
        }
        that.setData({
          couponLis: res.data.data,
          couponIndex: that.data.couponIndex,
          ticker_price: that.data.ticker_price,
          pay_price: that.data.pay_price,
          total_price: that.data.total_price
        })
        console.log(that.data.couponIndex)
      }
    })
  },
  coupon_alert_close() {
    this.setData({
      coupon_alert: true
    })
  },
  coupon_alert_btn() {
    var that = this
    that.data.couponIndex = ''
    that.data.pay_price = that.data.total
    that.data.ticker_price = 0
    that.data.total_price = that.data.total
    that.setData({
      coupon_alert: true,
      couponIndex: that.data.couponIndex,
      ticker_price: that.data.ticker_price,
      pay_price: that.data.pay_price,
      total_price: that.data.total_price
    })
  },
  onHide() {
    getApp().endpage(new Date().getTime())
  }
})